* Construct Main Regression Tables ******************************************

local folder `1'
local rte_opts `2'   
local table_tags `3'   
local vestypes "`4'"
local eca_ys `5'
local report_extra_mean `6' 
local report_spillover `7'

**** Regression options that don't change
local controls IFO LS 
local vce "cluster ves_id"			

preserve 

foreach tag of local table_tags {
	
	* update labels, b/c changed in some procedures above
	label var dist_eca2009 "ECA Dist, (km)"
	label var f_eca09_cons "ECA Fuel, (t)"
	label var dist_eca2011 "ECA Dist, (km)"
	label var f_eca11_cons "ECA Fuel, (t)"
	label var avg_speed_eca2009 "ECA Speed, (km/h)"
	label var avg_speed_eca2011 "ECA Speed, (km/h)"
	label var avg_speed "Speed, (km/h)"
	
	foreach eca_y of local eca_ys {
	
		* setting these to a number as a place holder
		* resetting at end of loop
		mvencode avg_speed_eca`eca_y' , mv(-9999)
		
		if `eca_y' == 2009 {
			local run t_eca09
			local cut eca1
			local y_tag "09"
			
			local bw 150
			local donut 0 
			
		}
		if `eca_y' == 2011 {
			local run t_eca11 
			local cut eca2
			local y_tag "11"
			
			local bw 150
			local donut 0 
			
		}
		
		if `eca_y' == 2012 {
			local run t_eca12 
			local cut eca3
			local y_tag "11" // which CA ECA to use
			
			local bw 150
			local donut 0 
			
		}
		
		if `eca_y' == 2015 {
			local run t_eca15 
			local cut eca5
			local y_tag "11" // which CA ECA to use
			
			local bw 150
			local donut 0 
		}
		
				
		* getting mean fuel prices for predictions
		* days pre ECA
		local t_opts 30 0
		foreach t of local t_opts {
			sum LS if `run'==-`t'
			local LSmean`t' = r(mean)
			sum IFO if `run'==-`t'
			local IFOmean`t' = r(mean)
		}		
		
		if "`tag'" == "main" {
		* main tables in paper (post 5/2021)
		if `eca_y' == 2009 {
				local yvars dist_eca`eca_y' avg_speed_eca`eca_y' f_eca`y_tag'_cons cost_eca`y_tag'_cons e_pm_eca`y_tag'_cons td_inm_eca`y_tag'_cons 
			}
			else {
				* local yvars dist_eca`eca_y' f_eca`y_tag'_cons e_pm_comply_cons_ineca11 cost_comply_cons td_inm_comply_cons /
				* local yvars dist_eca`eca_y' avg_speed_eca`eca_y' f_eca`y_tag'_cons cost_eca09_cons td_inm_eca09_cons 
				local yvars dist_eca`eca_y' avg_speed_eca`eca_y' f_eca`y_tag'_cons cost_eca`y_tag'_cons e_pm_eca`y_tag'_cons td_inm_eca`y_tag'_cons  
			}
			local log_y ""
		
		}
		
		if "`tag'" == "main_supp" {
		* supplemental tables in paper (post 5/2021)
			local yvars dist f_cons SBind hours e_pm_dist_eca`y_tag'_cons
			local log_y ""
		}
		
		if "`tag'" == "main_unex" {
		* main tables in paper for unexposed routes
			local yvars dist avg_speed f_cons cost_eca`y_tag'_cons e_pm_eca`y_tag'_cons td_inm_eca`y_tag'_cons 
			local log_y ""
		}
		
		if "`tag'" == "robust" {
			if `eca_y' == 2009 {
				local yvars cost_eca09_cons cost_eca09_cons_blend td_inm_eca09_cons td_inm_eca09_cons_blend td_eca09_cons 
			}
			else {
				local yvars cost_comply_cons cost_comply_cons_blend  td_inm_comply_cons td_inm_comply_cons_blend td_comply_cons  
			}
			local log_y ""
		}
		
		if "`tag'"=="xvars" {
			local yvars built dwt loa draft power_kw USflag // IFO LS 
			local log_y ""
		}
				
		if "`tag'" == "welfare_levels" {
		* these are tables use for welfare analysis matlab code
			if `eca_y' == 2009 {
				local yvars dist_eca`eca_y' f_eca`y_tag'_cons dist f_cons cost_comply_cons td_inm_comply_cons cost_eca09_cons td_inm_eca09_cons td_nox_cons td_comply_cons td_eca09_cons e_pm_comply_cons_ineca09 e_pm_dist_eca09_cons e_pm_comply_cons e_pm_eca09_cons e_so2_comply_cons_ineca09 e_so2_dist_eca09_cons e_so2_comply_cons e_so2_eca09_cons hours	
			}
			else {
				local yvars dist_eca`eca_y' f_eca`y_tag'_cons dist f_cons cost_comply_cons td_inm_comply_cons td_nox_cons hours
			}
			local log_y ""
		}
								
		
		************************************************************************
		* default route fixed effects
		local rte_fe route_id
		
		* entrance/exit fixed effects
		* update route fixed effects for NA ECA 
		* don't want to include, to get at broader substitutions
		local rte_fe_exits "`rte_fe'"
		if (`eca_y'==2012) | (`eca_y'==2015)  {
			local rte_fe_exits sample_cond // using the sample indicator b/c all ones
		}	
				
		foreach rte_opt of local rte_opts {
	
			* set route options
			if "`rte_opt'"=="all_coast" {
				local rte_cond 	`"inlist(port_agg,"SoCal","NoCal") & route_type=="Coastal" "' 
				local samp_rte "(sample_RD_regs==1)"
			}
						
			if "`rte_opt'"=="all_exits" {
				local rte_cond 	`"inlist(port_agg,"SoCal","NoCal") & route_type=="EnterExit"  "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
									
			if "`rte_opt'"=="socal_coast" {
				local rte_cond 	`"port_agg=="SoCal" & route_type=="Coastal" "' 
				local samp_rte "(sample_RD_regs==1)"
			}
					
			if "`rte_opt'"=="socal_exits" {
				local rte_cond 	`"port_agg=="SoCal" & route_type=="EnterExit"  "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
						
			if "`rte_opt'"=="socal_exits_south0" {
				local rte_cond 	`"port_agg=="SoCal" & route_type=="EnterExit" & south==0 "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
						
			
			if "`rte_opt'"=="socal_exits_south1" {
				local rte_cond 	`"port_agg=="SoCal" & route_type=="EnterExit" & south==1 "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
			
						
			if "`rte_opt'"=="nocal_coast" {
				local rte_cond 	`"port_agg=="NoCal" & route_type=="Coastal" "' 
				local samp_rte "(sample_RD_regs==1)"
			}
						
			if "`rte_opt'"=="nocal_exits" {
				local rte_cond 	`"port_agg=="NoCal" & route_type=="EnterExit" "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
						
			if "`rte_opt'"=="other_coast" {
				local rte_cond 	`"port_agg=="OtherWC" & route_type=="Coastal" "' 
				local samp_rte "(sample_RD_regs==1)"
			}
			
			if "`rte_opt'"=="other_exits" {
				local rte_cond 	`"port_agg=="OtherWC" & route_type=="EnterExit" "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
			
			if "`rte_opt'"=="other_all" {
				local rte_cond 	`"port_agg=="OtherWC" & inlist(route_type,"EnterExit","Coastal") "' 
				local samp_rte "(sample_RD_regs==1)"
				local rte_fe "`rte_fe_exits'"
			}
			
			capture drop sample_cond
			gen sample_cond = `samp_rte' & (`run'<=`bw') & (`run'>=-`bw') & ( `run'<-`donut' | `run'>`donut' )	
				
			foreach vestype of local vestypes {
			
				local vestype2 : subinstr local vestype " " ""	
				local apprep replace
								
				if `"`vestype'"'=="Container" {
					local fe "i.`rte_fe'#i.ves_id" 
					local ves_controls
					local trends i.`cut'#c.`run'#i.`rte_fe'					
				}
				if "`vestype'"=="Other Cargo" {
					local fe "i.`rte_fe'"
					local ves_controls built dwt loa draft beam power_kw USflag group_agg_i
					local trends i.`cut'#c.`run'#i.`rte_fe'
				}
				if "`vestype'"=="Tanker" {
					local fe "i.`rte_fe'"
					local ves_controls built dwt loa draft beam power_kw USflag group_agg_i
					local trends i.`cut'#c.`run'#i.`rte_fe'
				}
				
				
				* if doing xvars table then remove controls and do route FE
				if "`tag'"=="xvars" {
					local fe "i.`rte_fe'"
					local ves_controls
				}
												
				foreach yvar of local yvars {	
						
					* addressing labels
					if "`rte_opt'"=="unex" & ( "`yvar'"=="dist_eca`eca_y'" | "`yvar'"=="f_eca`y_tag'_cons" ) {
						capture drop ltmp
						capture drop tmp
						gen ltmp = 0 
						gen tmp = 0 
						
						* add labels
						local lbl : variable label `yvar'
						label var tmp `"`lbl'"' 
						
						local lbl : variable label l`yvar'
						label var ltmp `"`lbl'"'
						
						local yvar tmp
					}
					
					local log_y_use `log_y'
					if "`yvar'" == "SBind" {
						local log_y_use "" 
					}
					
					* removing routes with less than 5 obs in pre and post samples
					capture drop rte_cnts_ok
					capture drop cnts cnts_5 has_cnts
					egen cnts = count(dist) if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'" , by(`rte_fe' `cut')
					bysort `rte_fe' `cut' : gen cnts_5 = (cnts>5) if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'"
					egen has_cnts = mean(cnts_5) if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'" , by(`rte_fe')
					gen rte_cnts_ok = (has_cnts==1)
					drop cnts cnts_5 has_cnts
					
					
					* calculating change in total and specifying formula for spillover
					if ~ ( ( "`rte_opt'"=="other_all" ) | ( "`rte_opt'"=="other_coast" ) | ( "`rte_opt'"=="other_exits" ) ) & `report_spillover'==1{
						
						* setting default
						if ("`tag'" == "main_levels") {	
							local perc_text ", % of no adjust cf., -9999 "
							local spill_text " , Spillover ratio, -9999 " 
						}
						
						* not displaying spillover by default
						if ("`tag'" == "main_supp_levels") | ("`tag'" == "robust_all")  {	
							local perc_text ", % of no adjust cf., -9999 "
							local spill_text  
						}
						
						* not displaying spillover by default
						if ("`tag'" == "main") {	
							local perc_text 
							local spill_text " , Spillover ratio, -9999 "  
						}
						
						if "`yvar'" == "dist_eca2009" | "`yvar'" == "dist_eca2011" {
							reghdfe dist `cut' `trends' `controls' `ves_controls' /// 
								if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'" & rte_cnts_ok , absorb(`fe') vce(`vce')
							local delta_tot = _b[`cut']
							local spill_text ", Spillover ratio, ( 1 - ( `delta_tot' / _b[`cut'] ) ) "
						}
						if "`yvar'" == "f_eca09_cons" | "`yvar'" == "f_eca11_cons" {
							reghdfe f_cons `cut' `trends' `controls' `ves_controls' /// 
								if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'" & rte_cnts_ok, absorb(`fe') vce(`vce')
							local delta_tot = _b[`cut']
							local spill_text ", Spillover ratio , ( 1 - ( `delta_tot' / _b[`cut'] ) ) "
						}
						if ("`yvar'" == "e_pm_comply_cons_ineca09" ) | ("`yvar'" == "e_pm_comply_cons_ineca11") {
							reghdfe e_pm_comply_cons  `cut' `trends' `controls' `ves_controls' /// 
								if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'" & rte_cnts_ok , absorb(`fe') vce(`vce')
							local delta_tot = _b[`cut']
							local spill_text ", Spillover ratio, ( 1 - ( `delta_tot' / _b[`cut'] ) ) "
						}
						
						* adding percent changes relative to no cf
						if "`yvar'" == "cost_eca09_cons" {
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_cost_comply_cons' - _b[`cut'] ) ) )"
						} 
						if "`yvar'" == "td_inm_eca09_cons" {
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_td_inm_comply_cons' - _b[`cut'] ) ) )"
						}
						if "`yvar'" == "e_pm_eca09_cons" { 
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_e_pm_comply_cons' - _b[`cut'] ) ) )"
						}
						if "`yvar'" == "cost_eca09_cons_blend" { 
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_cost_comply_cons_blend' - _b[`cut'] ) ) )"
						}
						if "`yvar'" == "td_inm_eca09_cons_blend" { 
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_td_inm_comply_cons_blend' - _b[`cut'] ) ) )"
						} 
						if "`yvar'" == "td_eca09_cons" { 
							local perc_text ", % of no adjust cf., ( 100 * ( _b[`cut'] / ( `beta_td_comply_cons' - _b[`cut'] ) ) )"
						} 
																		
						* not reporting percent for 2011
						if `eca_y' == 2011  {
							local perc_text 
						}
						
						* not displaying for main
						if ("`tag'" == "main") | ("`tag'" == "robust") {	
							local perc_text 
						}
						
					}
					else {
						* not reporting these for unexposed
						local perc_text 
						local spill_text 					
					}
										
					* regression and write to table
					local out_file "`folder'/rd_`tag'_`rte_opt'_`eca_y'_`vestype2'.tex"
					reghdfe `log_y_use'`yvar' `cut' `trends' `controls' `ves_controls' ///
						if sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'"  & rte_cnts_ok , absorb(`fe') vce(`vce')
					estimates store regresults
					local beta_`yvar' = _b[`cut']					
										
					* predicting outcome at t=0 and t=-30
					margins if e(sample) & `cut'==0 , predict(xb) at( `run'=( -30 ) LS=(`LSmean30') IFO=(`IFOmean30') ) /// 
																  at( `run'=( 0 ) LS=(`LSmean0') IFO=(`IFOmean0') )  post
					*margins, coeflegend
					*display "`cut'"
					*asdsad

					local mean_t30 = _b[1bn._at]
					local mean_t0 = _b[2._at]	
								
					if `report_extra_mean'==1 {
						local mean_text ", Mean (t=0) , `mean_t0', Mean (t=-30), `mean_t30'"
					}
					else {
						local mean_text ", Mean (t=0) , `mean_t0'"
					}
								
					estimates restore regresults
				
					* add baseline and percentage change
					*sum `yvar' if e(sample) & `cut'==0 
					*local mean = r(mean)
									
					if "`log_y'"=="l" {
						* Unused, but needs updates to work
						local chng_text ", Level change , ( `mean' * ( exp( _b[`cut']) - 1  ) )"
												
					}
					if "`log_y'"~="l" {
						local chng_text ", % change , ( ( _b[`cut'] / (`mean_t0' + 0.000000001 ) ) * 100 )"
					}
										
					* getting rid of spillover and percent text if not significant at 5\%
					if ( (2 * ttail(e(df_r), abs(_b[`cut']/_se[`cut']))) > 0.1 ) & "`spill_text'"~="" & `report_spillover'==1 {
						local spill_text " , Spillover ratio, -9999 " 
						*local perc_text
					}
					
					* calculating difference between dist and resid outcomes in pre-period
					* only adding if there is variable with _d tag
					* and setting perc_text to empty				
					noi capture {
						sum `yvar'_d if `cut'==0 & sample_cond==1 & `rte_cond' & vesseltype_regstr=="`vestype'"  & rte_cnts_ok						
						local cf_val = r(mean)
					}
					
					if _rc==0 & r(mean)!=0  { 
						if abs(100 * _b[`cut'] / `cf_val') < 200 {
							local cf_text ", $\Delta$ no behave , `cf_val' , % of no behave , 100 * _b[`cut'] / `cf_val' "	
						} 
						else {
							local cf_text 
						}
					}
					else {
						local cf_text 
					}
					
					outreg2 using `out_file', `apprep' lab keep( `cut' ) tex(frag) nonotes nocon /// 
					addstat(Vessels , e(N_clust)  `mean_text'  `chng_text' `spill_text' `perc_text' `cf_text')  
					local apprep append
												
					capture drop ltmp
					capture drop tmp
										
										
				}
			}

		}
		
	mvdecode avg_speed_eca`eca_y' , mv(-9999)
	}
	
}

restore
